
#include "message.hpp"
#include "net.hpp"
#include "dispatcher.hpp"
#include <thread>


void onRpcResponse(const gmrpc::BaseConnection::ptr &conn, gmrpc::RpcResponse::ptr &msg)
{
    std::cout << "收到了Rpc响应： " <<std::endl;
    std::string body = msg->serialize();
    std::cout << body << std::endl;
}

void onTopicResponse(const gmrpc::BaseConnection::ptr &conn, gmrpc::TopicResponse::ptr &msg)
{
    std::cout << "收到了Topic响应： " <<std::endl;
    std::string body = msg->serialize();
    std::cout << body << std::endl;
}


int main()
{
    auto dispatcher = std::make_shared<gmrpc::Dispatcher>();

    dispatcher->registerHandler<gmrpc::RpcResponse>(gmrpc::MType::RSP_RPC,onRpcResponse);//注册映射关系
    dispatcher->registerHandler<gmrpc::TopicResponse>(gmrpc::MType::RSP_TOPIC,onTopicResponse);//注册映射关系

    auto client = gmrpc::ClientFactory::create("127.0.0.1", 9090);
    auto message_cb = std::bind(&gmrpc::Dispatcher::onMessage,dispatcher.get(),
    std::placeholders::_1,std::placeholders::_2);

    client->setMessageCallback(message_cb);

    client->connect();

    auto rpc_req = gmrpc::MessageFactory::create<gmrpc::RpcRequest>();
    rpc_req->setId("11111");
    rpc_req->setMType(gmrpc::MType::REQ_RPC);
    rpc_req->setMethod("Add");
    Json::Value param;
    param["num1"] = 11;
    param["num2"] = 22;
    rpc_req->setParams(param);
    std::cout <<"-----------------------"<<std::endl;
    client->send(rpc_req);
    std::cout <<"-----------------------"<<std::endl;


    auto topic_req = gmrpc::MessageFactory::create<gmrpc::TopicRequest>();
    topic_req->setId("22222");
    topic_req->setMType(gmrpc::MType::REQ_TOPIC);
    topic_req->setOptype(gmrpc::TopicOptype::TOPIC_CREATE);
    topic_req->setTopicKey("news");
    client->send(topic_req);

    std::this_thread::sleep_for(std::chrono::seconds(10));
    client->shutdown();
    return 0;
}